<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class CangkuKuwei extends BaseController
{
    /**
     * 获取库位列表
     */
    public function getShelfList()
    {


        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
           // return json(['code' => 403, 'msg' => '权限不足']);
        }

        // 获取分页参数
        $page = Request::param('pageNo/d', 1);
        $limit = Request::param('pageSize/d', 20);
        $shelfCode = Request::param('shelfCode/s', '');
        
        // 构建查询
        $query = Db::name('shelf');
        
        // 关键字搜索
        if (!empty($shelfCode)) {
            $query = $query->where('shelf_code', 'like', "%{$shelfCode}%");
        }

        // 获取总记录数
        $total = $query->count();
        
        // 获取分页数据
        $list = $query
            ->field([
                'id',
                'shelf_code',
                'description',
                'create_time',
                'update_time'
            ])
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select();
            
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'total' => $total,
                'list' => $list
            ]
        ]);
    }
    
    /**
     * 添加库位
     */
    public function addShelf()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
           // return json(['code' => 403, 'msg' => '权限不足']);
        }
        
        // 获取请求参数
        $data = [
            'shelf_code' => Request::param('shelf_code/s', ''),
            'description' => Request::param('description/s', ''),
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        // 参数验证
        if (empty($data['shelf_code'])) {
            return json(['code' => 400, 'msg' => '库位编号不能为空']);
        }
        
        // 检查库位编号是否已存在
        $exists = Db::name('shelf')->where('shelf_code', $data['shelf_code'])->find();
        if ($exists) {
            return json(['code' => 400, 'msg' => '库位编号已存在']);
        }
        
        // 添加库位
        try {
            $id = Db::name('shelf')->insertGetId($data);
            
            return json([
                'code' => 200,
                'msg' => '添加成功',
                'data' => ['id' => $id]
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            trace('添加库位失败: ' . $e->getMessage(), 'error');
            return json([
                'code' => 500,
                'msg' => '添加失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 编辑库位
     */
    public function editShelf()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
            return json(['code' => 403, 'msg' => '权限不足']);
        }
        
        // 获取请求参数
        $id = Request::param('id/d', 0);
        if ($id <= 0) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $data = [
            'shelf_code' => Request::param('shelf_code/s', ''),
            'description' => Request::param('description/s', ''),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        // 参数验证
        if (empty($data['shelf_code'])) {
            return json(['code' => 400, 'msg' => '库位编号不能为空']);
        }
        
        // 检查库位是否存在
        $shelf = Db::name('shelf')->where('id', $id)->find();
        if (!$shelf) {
            return json(['code' => 404, 'msg' => '库位不存在']);
        }
        
        // 如果修改了库位编号，检查新编号是否已存在
        if ($data['shelf_code'] !== $shelf['shelf_code']) {
            $exists = Db::name('shelf')->where('shelf_code', $data['shelf_code'])->where('id', '<>', $id)->find();
            if ($exists) {
                return json(['code' => 400, 'msg' => '库位编号已存在']);
            }
        }
        
        // 更新库位
        try {
            Db::name('shelf')->where('id', $id)->update($data);
            
            return json([
                'code' => 200,
                'msg' => '更新成功'
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            trace('更新库位失败: ' . $e->getMessage(), 'error');
            
            return json([
                'code' => 500,
                'msg' => '更新失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 删除库位
     */
    public function deleteShelf()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
            return json(['code' => 403, 'msg' => '权限不足']);
        }
        
        // 获取请求参数
        $id = Request::param('id/d', 0);
        $ids = Request::param('ids/s', '');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            if (!empty($id)) {
                // 检查库位是否被物料分类引用
                $used = Db::name('material_category')->where('shelf_id', $id)->find();
                if ($used) {
                    return json(['code' => 400, 'msg' => '该库位已被物料使用，无法删除']);
                }
                
                // 删除单个库位
                Db::name('shelf')->where('id', $id)->delete();
            } else {
                // 将字符串转为数组
                $idArr = explode(',', $ids);
                
                // 检查库位是否被物料分类引用
                $used = Db::name('material_category')->whereIn('shelf_id', $idArr)->find();
                if ($used) {
                    return json(['code' => 400, 'msg' => '选中的库位中有被物料使用的，无法删除']);
                }
                
                // 批量删除库位
                Db::name('shelf')->whereIn('id', $idArr)->delete();
            }
            
            return json([
                'code' => 200,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            trace('删除库位失败: ' . $e->getMessage(), 'error');
            return json([
                'code' => 500,
                'msg' => '删除失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取考勤设置详情
     */
    public function detail()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 获取请求参数
        $id = Request::param('id/d', 1); // 默认获取ID为1的记录
        
        // 查询考勤设置
        $setting = Db::name('checkin_setting')
            ->where('id', $id)
            ->find();
            
        if (!$setting) {
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => null
            ]);
        }
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $setting
        ]);
    }
    
    /**
     * 添加考勤设置
     */
    public function add()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
            return json(['code' => 403, 'msg' => '权限不足']);
        }
        
        // 获取请求参数
        $data = [
            'range' => Request::param('range/d', 100),
            'location' => Request::param('location/s', ''),
            'location_name' => Request::param('location_name/s', ''),
            'advance_time' => Request::param('advance_time/d', 30),
            'work_type' => Request::param('work_type/d', 1),
            'morning_start_time' => Request::param('morning_start_time/s', ''),
            'morning_end_time' => Request::param('morning_end_time/s', ''),
            'afternoon_start_time' => Request::param('afternoon_start_time/s', ''),
            'afternoon_end_time' => Request::param('afternoon_end_time/s', ''),
            'status' => Request::param('status/d', 1),
            'departments' => Request::param('departments/s', ''),
            'map_api_key' => Request::param('map_api_key/s', ''), // 添加地图API密钥字段
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        // 参数验证
        if (empty($data['location']) || empty($data['location_name'])) {
            return json(['code' => 400, 'msg' => '打卡地点不能为空']);
        }
        
        if ($data['work_type'] == 1) {
            if (empty($data['morning_start_time']) || empty($data['morning_end_time'])) {
                return json(['code' => 400, 'msg' => '上下班时间不能为空']);
            }
        } else if ($data['work_type'] == 2) {
            if (empty($data['morning_start_time']) || empty($data['morning_end_time']) || 
                empty($data['afternoon_start_time']) || empty($data['afternoon_end_time'])) {
                return json(['code' => 400, 'msg' => '上下班时间不能为空']);
            }
        } else {
            return json(['code' => 400, 'msg' => '上下班次数参数错误']);
        }
        
        // 添加考勤设置
        try {
            $id = Db::name('checkin_setting')->insertGetId($data);
            
            return json([
                'code' => 200,
                'msg' => '添加成功',
                'data' => ['id' => $id]
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            trace('添加考勤设置失败: ' . $e->getMessage(), 'error');
            return json([
                'code' => 500,
                'msg' => '添加失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 更新考勤设置
     */
    public function update()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
            return json(['code' => 403, 'msg' => '权限不足']);
        }
        
        // 获取请求参数
        $id = Request::param('id/d', 1);
        
        // 查询考勤设置是否存在
        $exists = Db::name('checkin_setting')->where('id', $id)->find();
        
        // 准备数据
        $data = [
            'range' => Request::param('range/d', 100),
            'location' => Request::param('location/s', ''),
            'location_name' => Request::param('location_name/s', ''),
            'advance_time' => Request::param('advance_time/d', 30),
            'work_type' => Request::param('work_type/d', 1),
            'morning_start_time' => Request::param('morning_start_time/s', ''),
            'morning_end_time' => Request::param('morning_end_time/s', ''),
            'afternoon_start_time' => Request::param('afternoon_start_time/s', ''),
            'afternoon_end_time' => Request::param('afternoon_end_time/s', ''),
            'status' => Request::param('status/d', 1),
            'departments' => Request::param('departments/s', ''),
            'map_api_key' => Request::param('map_api_key/s', ''), // 添加地图API密钥字段
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        // 参数验证
        if (empty($data['location']) || empty($data['location_name'])) {
            return json(['code' => 400, 'msg' => '打卡地点不能为空']);
        }
        
        if ($data['work_type'] == 1) {
            if (empty($data['morning_start_time']) || empty($data['morning_end_time'])) {
                return json(['code' => 400, 'msg' => '上下班时间不能为空']);
            }
        } else if ($data['work_type'] == 2) {
            if (empty($data['morning_start_time']) || empty($data['morning_end_time']) || 
                empty($data['afternoon_start_time']) || empty($data['afternoon_end_time'])) {
                return json(['code' => 400, 'msg' => '上下班时间不能为空']);
            }
        } else {
            return json(['code' => 400, 'msg' => '上下班次数参数错误']);
        }
        
        try {
            if ($exists) {
                // 更新记录
                Db::name('checkin_setting')
                    ->where('id', $id)
                    ->update($data);
                
                return json([
                    'code' => 200,
                    'msg' => '更新成功'
                ]);
            } else {
                // 创建记录
                $data['id'] = $id;
                $data['create_time'] = date('Y-m-d H:i:s');
                
                Db::name('checkin_setting')->insert($data);
                
                return json([
                    'code' => 200,
                    'msg' => '创建成功'
                ]);
            }
        } catch (\Exception $e) {
            // 记录错误日志
            trace('考勤设置保存失败: ' . $e->getMessage(), 'error');
            
            return json([
                'code' => 500,
                'msg' => '操作失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 删除考勤设置
     */
    public function delete()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 检查用户权限
        $isAdmin = $this->checkAdminPermission($user['id']);
        if (!$isAdmin) {
            return json(['code' => 403, 'msg' => '权限不足']);
        }
        
        // 获取请求参数
        $ids = Request::param('ids/s', '');
        
        if (empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 将字符串转为数组
        $idArr = explode(',', $ids);
        
        // 删除考勤设置
        try {
            Db::name('checkin_setting')
                ->whereIn('id', $idArr)
                ->delete();
            
            return json([
                'code' => 200,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            trace('删除考勤设置失败: ' . $e->getMessage(), 'error');
            return json([
                'code' => 500,
                'msg' => '删除失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 获取当前有效的考勤设置
     */
    public function getCurrentSetting()
    {

        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        
        
        // 查询当前有效的考勤设置
        $setting = Db::name('checkin_setting')
            ->where('status', 1)
            ->order('id', 'desc')
            ->find();
            
        if (!$setting) {
            return json([
                'code' => 404,
                'msg' => '未找到有效的考勤设置'
            ]);
        }
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $setting
        ]);
    }

    /**
     * 检查用户是否有管理员权限
     */
    private function checkAdminPermission($userId)
    {
        // 检查用户是否为管理员或有管理权限
        // 方法1: 检查用户是否为部门负责人
        $isLeader = Db::name('user')
            ->where('id', $userId)
            ->where('is_leader', 1)
            ->find();
        
        if ($isLeader) {
            return true;
        }
        
        // 方法2: 检查用户是否为管理部门成员
        $isAdmin = Db::name('user_department_relation')
            ->where('user_id', $userId)
            ->where('department_id', 1) // 假设部门ID=1为管理部门
            ->find();
        
        return !empty($isAdmin);
    }
} 